﻿using System;

namespace HikvisionDemo
{
    class PreviewUtils
    {
        // 实时预览

        public static int RealPlay(int userId, IntPtr hPlayWnd)
        {
            int realPlayHandle = -1;

            // 预览参数
            CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
            lpPreviewInfo.hPlayWnd = hPlayWnd;//预览窗口
            lpPreviewInfo.lChannel = 1;//预te览的设备通道
            lpPreviewInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
            lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
            lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
            lpPreviewInfo.dwDisplayBufNum = 1; //播放库播放缓冲区最大缓冲帧数
            lpPreviewInfo.byProtoType = 0;
            lpPreviewInfo.byPreviewMode = 0;

            IntPtr pUser = new IntPtr();//用户数据

            //打开预览
            realPlayHandle = CHCNetSDK.NET_DVR_RealPlay_V40(userId, ref lpPreviewInfo, null/*RealData*/, pUser);
            if (realPlayHandle < 0)
            {
                uint iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                Console.WriteLine($"预览失败，句柄={realPlayHandle}，错误代码={iLastErr}");
            }
            else
            {
                Console.WriteLine($"预览成功，句柄={realPlayHandle}");
            }

            return realPlayHandle;
        }

        public static bool StopRealPlay(int realPlayHandle)
        {
            // 停止预览
            bool result = false;
            if (realPlayHandle >= 0)
            {
                result = CHCNetSDK.NET_DVR_StopRealPlay(realPlayHandle);
                if (result)
                {
                    Console.WriteLine($"停止预览成功，句柄={realPlayHandle}");
                }
                else
                {
                    uint iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    Console.WriteLine($"停止预览失败，句柄={realPlayHandle}，错误代码={iLastErr}");
                }
            }
            return result;
        }

        public static bool CapturePicture(int userId)
        {
            // 抓图
            bool result = false;

            // 图片保存名称
            string pictureName = "JPEG_test.jpg";

            // 通道号
            int channel = 1;

            CHCNetSDK.NET_DVR_JPEGPARA lpJpegPara = new CHCNetSDK.NET_DVR_JPEGPARA();
            lpJpegPara.wPicQuality = 0; //图像质量 Image quality
            lpJpegPara.wPicSize = 0xff; //抓图分辨率 Picture size: 2- 4CIF，0xff- Auto(使用当前码流分辨率)，抓图分辨率需要设备支持，更多取值请参考SDK文档

            result = CHCNetSDK.NET_DVR_CaptureJPEGPicture(userId, channel, ref lpJpegPara, pictureName);
            if (result)
            {
                Console.WriteLine($"{userId}抓图成功！");
            }
            else
            {
                uint iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                Console.WriteLine($"{userId}抓图失败，错误代码={iLastErr}");
            }

            return result;
        }

    }
}
